//解析文件表单的第三方插件
const formidable = require('formidable');
const path = require('path');
//文章集合
const {Article} = require('../../model/article');

module.exports = async (req, res) => {
    //创建表单解析对象
    const form = new formidable.IncomingForm();
    //配置上传文件的存放位置
    form.uploadDir = path.join(__dirname, '../', '../', 'public', 'uploads');
    //保留上传文件的后缀
    form.keepExtensions = true;
    //解析表单
    form.parse(req, async (err, fields, files) => {
        //err为错误对象，解析失败存储错误信息，成功为null
        //fields对象类型保存普通表单数据
        //files对象类型保存了和上传文件相关的数据
        let {title, author, publishDate, content} = fields;
        if (publishDate == '') publishDate = Date.now();

        await Article.create({
            title,
            author,
            publishDate,
            content,
            cover: files.cover.path.split('public')[1]
        });
        //将页面重定向到文章列表页面
        res.redirect('/admin/article');
    });

};
